package com.fzy.core.spring;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.fzy.core.entity.Page;

public class MyRowMapperResultSetExtractor implements ResultSetExtractor {
	private static final Logger log = LoggerFactory.getLogger(MyRowMapperResultSetExtractor.class);
	RowMapper rowMapper;
	Page page;

	public MyRowMapperResultSetExtractor(RowMapper rowMapper, Page page) {
		this.rowMapper = rowMapper;
		this.page = page;
	}

	public Object extractData(ResultSet rs) throws SQLException {
		if (page == null)
			return page;
		List results = new LinkedList();
		rs.last();
		page.setTotalCount(rs.getRow());
		long pageNo = page.getPageNoLong();
		long pageSize = page.getPageSizeLong();
		int beforeCurrentPageFirst = (int)(((pageNo - 1) * pageSize));
//		if (beforeCurrentPageFirst == 0)
//			rs.beforeFirst();
//		else
//			rs.absolute(beforeCurrentPageFirst);
//		log.debug("======beforeCurrentPageFirst:" + beforeCurrentPageFirst);
		
		rs.beforeFirst();

		int count = 0;
		while (rs.next() && count < beforeCurrentPageFirst + pageSize) {
			if(count >= beforeCurrentPageFirst){
				results.add(this.rowMapper.mapRow(rs, beforeCurrentPageFirst
						+ count));
			}
			count++;
		}
		page.setResult(results);
		return page;
	}

}
